#include "string.h"
#include "app_common.h"
#include "cJSON/cJSON.h"
#include "stdlib.h"
#include "log/log.h"
/**
 * @brief 将字符数组格式消息转换为json格式消息
 * @param chars 字符数组
 * @param len   字符数组数据长度
 * @return json消息
 */
/**
 * 字符数组 ： 1  2  4  XXabcd
 * json字符串：{"conn_type":1,"id":"5858","msg":"61626364"}
 */
char *app_message_charsToJson(char *chars,int len)
{
    // 从chars中取出:conn_type/id_len/msg_len/id/msg
    int conn_type = chars[0];
    int id_len = chars[1];
    int msg_len = chars[2];
    char id[id_len];
    char msg[msg_len];
    memcpy(id,chars+3,id_len);
    memcpy(msg,chars+3+id_len,msg_len);

    // 将id和msg转换为十六进制字符串： app_common_charToHexstr
    char *id_hexstr = app_common_charsToHexstr(id,id_len);
    char *msg_hexstr = app_common_charsToHexstr(msg,msg_len);

    // 生成包含conn_type/id_hexstr/msg_hexstr的json字符串
    cJSON *root_obj = cJSON_CreateObject();

    cJSON_AddNumberToObject(root_obj,"conn_type",conn_type);
    cJSON_AddStringToObject(root_obj,"id",id_hexstr);
    cJSON_AddStringToObject(root_obj,"msg",msg_hexstr);
    char *json = cJSON_PrintUnformatted(root_obj);
    // 释放内存
    cJSON_Delete(root_obj);
    free(id_hexstr);
    free(msg_hexstr);
    // 返回json
    return json;
}

/**
 * @brief 将json格式消息转换为字符数组格式消息
 * @param json  json消息
 * @param chars_buf 字符数组消息的缓存容器
 * @param buf_len   缓存容器大小
 * @return 成功: 字符数组消息的长度，失败:-1
 */
/**
 * 字符数组 ： 1  2  4  XXabcd
 * json字符串：{"conn_type":1,"id":"5858","msg":"61626364"}
 */
int app_message_jsonToChars(char *json,char *chars_buf,int buf_len)
{
    // 解析json，得到:conn_type/id_hexstr/msg_hexstr
    cJSON *root_obj = cJSON_Parse(json);
    int conn_type = cJSON_GetObjectItem(root_obj,"conn_type")->valueint;
    char *id_hexstr = cJSON_GetObjectItem(root_obj,"id")->valuestring;
    char *msg_hexstr = cJSON_GetObjectItem(root_obj,"msg")->valuestring;

    // 将十六进制字符串id_hexstr/msg_hexstr转换为字符数组：app_common_hexstrToChars
    int id_len = -1;
    int msg_len = -1;
    char *id_chars = app_common_hexstrToChars(id_hexstr,&id_len);
    char *msg_chars = app_common_hexstrToChars(msg_hexstr,&msg_len);

    // 字符数组消息的长度
    int chars_len = 3 + id_len + msg_len;
    // 检查容器是否够大
    if(chars_len > buf_len)
    {
        log_error("buf_len is too small");
        return -1;
    }
    // 将conn_type/id_len/msg_len/id/msg写入容器
    chars_buf[0] = conn_type;
    chars_buf[1] = id_len;
    chars_buf[2] = msg_len;
    memcpy(chars_buf+3,id_chars,id_len);
    memcpy(chars_buf+3+id_len,msg_chars,msg_len);

    cJSON_Delete(root_obj);
    free(id_chars);
    free(msg_chars);
    // 返回字符数组消息的长度
    return chars_len;

}
